<?php
if (!defined('ABSPATH')) { exit; }

// 获取安全模块实例检查许可证状态
$security = wp_spider_premium_security();
$is_premium = $security->is_premium_activated();

// 获取当前日期
$today = current_time('Y-m-d');
$yesterday = date('Y-m-d', strtotime('-1 day'));
$week_ago = date('Y-m-d', strtotime('-7 days'));
$month_ago = date('Y-m-d', strtotime('-30 days'));
?>

<div class="wrap">
    <h1>🕷️ 蜘蛛概况</h1>
    <p class="description">查看网站各大搜索引擎蜘蛛来访的数据统计和分析</p>
    
    <!-- 今日蜘蛛统计卡片 -->
    <div class="spider-overview-cards">
        <div class="overview-card">
            <div class="card-header">
                <h3>今日蜘蛛</h3>
                <span class="card-date"><?php echo $today; ?></span>
            </div>
            <div class="card-content" id="today-spider-stats">
                <div class="stat-item">
                    <div class="stat-value" id="today-spider-count">-</div>
                    <div class="stat-label">来访蜘蛛数</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value" id="today-url-count">-</div>
                    <div class="stat-label">爬取URL数</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value" id="today-avg-urls">-</div>
                    <div class="stat-label">平均爬取URL数</div>
                </div>
            </div>
        </div>
        
        <div class="overview-card">
            <div class="card-header">
                <h3>昨日对比</h3>
                <span class="card-date"><?php echo $yesterday; ?></span>
            </div>
            <div class="card-content" id="yesterday-spider-stats">
                <div class="stat-item">
                    <div class="stat-value" id="yesterday-spider-count">-</div>
                    <div class="stat-label">来访蜘蛛数</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value" id="yesterday-url-count">-</div>
                    <div class="stat-label">爬取URL数</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value" id="yesterday-avg-urls">-</div>
                    <div class="stat-label">平均爬取URL数</div>
                </div>
            </div>
        </div>
        
        <div class="overview-card">
            <div class="card-header">
                <h3>30天平均</h3>
                <span class="card-date">最近30天</span>
            </div>
            <div class="card-content" id="monthly-spider-stats">
                <div id="monthly-premium-notice" class="premium-notice" style="display: none;">
                    <div class="premium-restriction">
                        <span class="premium-icon">🔒</span>
                        <span class="premium-text">30天平均功能需要激活PRO版本</span>
                        <a href="<?php echo admin_url('admin.php?page=spider-license'); ?>" class="premium-link">立即激活</a>
                    </div>
                </div>
                <div class="stat-item">
                    <div class="stat-value" id="monthly-spider-count">-</div>
                    <div class="stat-label">平均蜘蛛数</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value" id="monthly-url-count">-</div>
                    <div class="stat-label">平均URL数</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value" id="monthly-avg-urls">-</div>
                    <div class="stat-label">平均爬取URL数</div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 趋势图 -->
    <div class="spider-trend-section">
        <div class="section-header">
            <h2>📈 蜘蛛访问分析</h2>
            <div class="trend-controls">
                <select id="trend-period">
                    <option value="today">今天</option>
                    <option value="yesterday">昨天</option>
                    <option value="week" class="premium-option" data-premium="true">最近7天 🔒</option>
                    <option value="month" class="premium-option" data-premium="true">最近30天 🔒</option>
                </select>
                <button id="toggle-comparison" class="button active">隐藏昨天数据</button>
            </div>
        </div>
        
        <!-- 左右分栏布局 -->
        <div class="trend-layout">
            <!-- 左侧：详细趋势图 -->
            <div class="trend-left-panel">
                <div class="panel-header">
                    <h3>🕷️ 蜘蛛访问趋势</h3>
                    <p class="panel-description">显示每个时间段的蜘蛛数量和类型</p>
                </div>
                <div class="trend-chart-container">
                    <canvas id="trend-chart" width="400" height="350"></canvas>
                </div>
                <div class="spider-details" id="spider-details">
                    <div class="details-header">
                        <h4>📊 蜘蛛详情</h4>
                    </div>
                    <div class="details-content" id="spider-details-content">
                        <div class="no-data">点击图表查看详细蜘蛛信息</div>
                    </div>
                </div>
            </div>
            
            <!-- 右侧：3D高级图表 -->
            <div class="trend-right-panel">
                <div class="panel-header">
                    <h3>⏱️ 响应时间分析</h3>
                    <p class="panel-description">展示各蜘蛛的平均响应时间分布</p>
                </div>
                <div class="chart-3d-container">
                    <canvas id="chart-3d" width="400" height="350"></canvas>
                </div>
                <div class="chart-controls">
                    <button id="rotate-3d" class="button button-secondary">🔄 旋转视图</button>
                    <button id="reset-3d" class="button button-secondary">🎯 重置视角</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Top10 统计 -->
    <div class="spider-top-section">
        <div class="top-tabs">
            <button class="tab-button active" data-tab="top-spiders">Top10蜘蛛</button>
            <button class="tab-button" data-tab="top-urls">Top10爬取URL</button>
            <button class="tab-button" data-tab="top-articles">Top10热门文章</button>
        </div>
        
        <div class="top-content">
            <div id="top-spiders" class="tab-content active">
                <div class="content-header">
                    <h3>Top10蜘蛛爬取统计</h3>
                    <select id="top-spiders-period">
                        <option value="today">今天</option>
                        <option value="yesterday">昨天</option>
                        <option value="week" class="premium-option" data-premium="true">最近7天 🔒</option>
                        <option value="month" class="premium-option" data-premium="true">最近30天 🔒</option>
                    </select>
                </div>
                <div class="top-list" id="top-spiders-list">
                    <div class="loading">加载中...</div>
                </div>
            </div>
            
            <div id="top-urls" class="tab-content">
                <div class="content-header">
                    <h3>Top10蜘蛛爬取URL</h3>
                    <select id="top-urls-period">
                        <option value="today">今天</option>
                        <option value="yesterday">昨天</option>
                        <option value="week" class="premium-option" data-premium="true">最近7天 🔒</option>
                        <option value="month" class="premium-option" data-premium="true">最近30天 🔒</option>
                    </select>
                </div>
                <div class="top-list" id="top-urls-list">
                    <div class="loading">加载中...</div>
                </div>
            </div>
            
            <div id="top-articles" class="tab-content">
                <div class="content-header">
                    <h3>Top10热门文章</h3>
                    <select id="top-articles-period">
                        <option value="today">今天</option>
                        <option value="yesterday">昨天</option>
                        <option value="week" class="premium-option" data-premium="true">最近7天 🔒</option>
                        <option value="month" class="premium-option" data-premium="true">最近30天 🔒</option>
                    </select>
                </div>
                <div class="top-list" id="top-articles-list">
                    <div class="loading">加载中...</div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.spider-overview-cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}

.overview-card {
    background: white;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    border: 1px solid #e1e5e9;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #f0f0f0;
}

.card-header h3 {
    margin: 0;
    color: #333;
    font-size: 16px;
}

.card-date {
    color: #666;
    font-size: 12px;
}

.card-content {
    display: flex;
    justify-content: space-between;
}

.stat-item {
    text-align: center;
    flex: 1;
}

.stat-value {
    font-size: 24px;
    font-weight: bold;
    color: #0073aa;
    margin-bottom: 5px;
}

.stat-label {
    font-size: 12px;
    color: #666;
}

.spider-trend-section {
    background: white;
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 30px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.section-header h2 {
    margin: 0;
    color: #333;
}

.trend-controls {
    display: flex;
    gap: 10px;
    align-items: center;
}

/* 趋势图布局 */
.trend-layout {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    margin-top: 20px;
}

.trend-left-panel,
.trend-right-panel {
    background: white;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    border: 1px solid #e1e5e9;
}

.panel-header {
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #e1e5e9;
}

.panel-header h3 {
    margin: 0 0 8px 0;
    color: #1d2327;
    font-size: 18px;
    font-weight: 600;
}

.panel-description {
    margin: 0;
    color: #646970;
    font-size: 13px;
}

.trend-chart-container {
    position: relative;
    height: 350px;
    margin-bottom: 20px;
}

.chart-3d-container {
    position: relative;
    height: 350px;
    margin-bottom: 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 8px;
    overflow: hidden;
}

/* 蜘蛛详情区域 */
.spider-details {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 15px;
    border: 1px solid #e1e5e9;
}

.details-header h4 {
    margin: 0 0 10px 0;
    color: #1d2327;
    font-size: 14px;
    font-weight: 600;
}

.details-content {
    max-height: 200px;
    overflow-y: auto;
}

.no-data {
    color: #646970;
    font-size: 13px;
    text-align: center;
    padding: 20px;
    font-style: italic;
}

.spider-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 12px;
    margin-bottom: 8px;
    background: white;
    border-radius: 6px;
    border: 1px solid #e1e5e9;
    transition: all 0.2s ease;
}

.spider-item:hover {
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    transform: translateY(-1px);
}

.spider-name {
    font-weight: 600;
    color: #1d2327;
    font-size: 13px;
}

.spider-count {
    background: #0073aa;
    color: white;
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 600;
}

.time-label {
    font-weight: 600;
    color: #0073aa;
    font-size: 13px;
    margin-bottom: 10px;
    padding: 5px 10px;
    background: #e3f2fd;
    border-radius: 4px;
    text-align: center;
}

/* 3D图表控制按钮 */
.chart-controls {
    display: flex;
    gap: 10px;
    justify-content: center;
}

.chart-controls .button {
    padding: 8px 16px;
    font-size: 12px;
    border-radius: 6px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
    .trend-layout {
        grid-template-columns: 1fr;
        gap: 15px;
    }
    
    .trend-chart-container,
    .chart-3d-container {
        height: 300px;
    }
}

.spider-top-section {
    background: white;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.top-tabs {
    display: flex;
    border-bottom: 1px solid #e1e5e9;
    margin-bottom: 20px;
}

.tab-button {
    background: none;
    border: none;
    padding: 10px 20px;
    cursor: pointer;
    border-bottom: 2px solid transparent;
    color: #666;
    font-size: 14px;
}

.tab-button.active {
    color: #0073aa;
    border-bottom-color: #0073aa;
}

.tab-content {
    display: none;
}

.tab-content.active {
    display: block;
}

.content-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.content-header h3 {
    margin: 0;
    color: #333;
}

.top-list {
    min-height: 200px;
}

.loading {
    text-align: center;
    color: #666;
    padding: 40px;
}

.top-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid #f0f0f0;
}

.top-item:last-child {
    border-bottom: none;
}

.top-item-info {
    flex: 1;
}

.top-item-name {
    font-weight: 500;
    color: #333;
    margin-bottom: 2px;
}

.top-item-details {
    font-size: 12px;
    color: #666;
}

.top-item-stats {
    text-align: right;
}

.top-item-count {
    font-weight: bold;
    color: #0073aa;
}

.top-item-percentage {
    font-size: 12px;
    color: #666;
}

.premium-notice {
    padding: 40px 20px;
    text-align: center;
    background: #f8f9fa;
    border-radius: 8px;
    border: 2px dashed #dee2e6;
}

.premium-restriction {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 15px;
    max-width: 400px;
    margin: 0 auto;
}

.premium-icon {
    font-size: 48px;
    color: #ff6b6b;
}

.premium-text {
    font-size: 16px;
    color: #495057;
    font-weight: 500;
}

.premium-link {
    display: inline-block;
    padding: 12px 24px;
    background: linear-gradient(135deg, #007cba, #005a87);
    color: white;
    text-decoration: none;
    border-radius: 6px;
    font-weight: 600;
    transition: all 0.3s ease;
    box-shadow: 0 2px 8px rgba(0, 124, 186, 0.3);
}

.premium-link:hover {
    background: linear-gradient(135deg, #005a87, #004066);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 124, 186, 0.4);
    color: white;
    text-decoration: none;
}
</style>

<script>
// 定义 ajaxurl 变量
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';

// 定义页面初始化函数
function initSpiderOverviewPage() {
    // 确保 jQuery 可用
    if (typeof jQuery === 'undefined') {
        console.error('jQuery 未加载，无法初始化页面');
        return;
    }
    
    var $ = jQuery;
    
    // 加载今日蜘蛛统计
    loadTodaySpiderStats();
    
    // 加载趋势图（今天/昨天免费，7天/30天需授权）
    loadTrendChart();
    
    // 加载响应时间分析（服务端验证）
    loadResponseTimeChart();
    
    // 加载Top10数据
    loadTopSpiders();
    
    // 标签页切换
    $('.tab-button').on('click', function() {
        $('.tab-button').removeClass('active');
        $(this).addClass('active');
        
        $('.tab-content').removeClass('active');
        $('#' + $(this).data('tab')).addClass('active');
        
        // 根据标签页加载对应数据
        const tab = $(this).data('tab');
        if (tab === 'top-spiders') {
            loadTopSpiders();
        } else if (tab === 'top-urls') {
            loadTopUrls();
        } else if (tab === 'top-articles') {
            loadTopArticles();
        }
    });
    
    // 趋势图周期切换
    $('#trend-period').on('change', function() {
        loadTrendChart();
        // 同步刷新响应时间分析
        loadResponseTimeChart();
    });
    
    // 对比按钮切换 - 现在控制昨天数据的显示/隐藏
    $('#toggle-comparison').on('click', function() {
        $(this).toggleClass('active');
        const isActive = $(this).hasClass('active');
        $(this).text(isActive ? '隐藏昨天数据' : '显示昨天数据');
        
        // 切换昨天数据集的可见性
        if (window.trendChart && window.trendChart.data && window.trendChart.data.datasets) {
            const datasets = window.trendChart.data.datasets;
            datasets.forEach((dataset, index) => {
                if (dataset.label && dataset.label.includes('昨天')) {
                    dataset.hidden = !isActive;
                }
            });
            window.trendChart.update();
        }
    });
    
    // 3D图表控制按钮
    $('#rotate-3d').on('click', function() {
        if (window.rotate3D) {
            if (window.isRotating) {
                window.isRotating = false;
                $(this).text('🔄 开始旋转');
            } else {
                window.isRotating = true;
                $(this).text('⏸️ 停止旋转');
                window.rotate3D();
            }
        }
    });
    
    $('#reset-3d').on('click', function() {
        if (window.chart3D) {
            window.chart3D.reset();
            window.isRotating = false;
            $('#rotate-3d').text('🔄 开始旋转');
        }
    });
    
    // Top10周期切换
    $('#top-spiders-period, #top-urls-period, #top-articles-period').on('change', function() {
        const tab = $(this).closest('.tab-content').attr('id');
        const period = $(this).val();
        
        // 简化验证：直接检查全局激活状态
        if (period === 'week' || period === 'month') {
            if (!window.wpSpiderMonitor || !window.wpSpiderMonitor.subscription || !window.wpSpiderMonitor.subscription.is_premium) {
                // 显示激活提示
                const $selectedOption = $(this).find('option:selected');
                if ($selectedOption.hasClass('premium-option')) {
                    alert('7天和30天数据查看需要激活PRO版本');
                    // 重置为今天
                    $(this).val('today');
                    return;
                }
            }
        }
        
        if (tab === 'top-spiders') {
            loadTopSpiders();
        } else if (tab === 'top-urls') {
            loadTopUrls();
        } else if (tab === 'top-articles') {
            loadTopArticles();
        }
    });
    
    function loadTodaySpiderStats() {
        // 确保 jQuery 可用
        if (typeof jQuery === 'undefined') {
            console.error('jQuery 未加载，无法加载今日蜘蛛统计');
            return;
        }
        
        var $ = jQuery;
        
        // 确保 ajaxurl 变量存在
        var ajaxUrl = typeof ajaxurl !== 'undefined' ? ajaxurl : '<?php echo admin_url('admin-ajax.php'); ?>';
        
        $.post(ajaxUrl, {
            action: 'spider_get_overview_stats',
            nonce: wpSpiderMonitor.nonce
        }, function(response) {
            if (response.success) {
                const data = response.data;
                $('#today-spider-count').text(data.today.spider_count || 0);
                $('#today-url-count').text(data.today.url_count || 0);
                $('#today-avg-urls').text(data.today.avg_urls || 0);
                
                $('#yesterday-spider-count').text(data.yesterday.spider_count || 0);
                $('#yesterday-url-count').text(data.yesterday.url_count || 0);
                $('#yesterday-avg-urls').text(data.yesterday.avg_urls || 0);
                
                // 处理30天平均数据的PRO版本限制
                if (data.is_premium) {
                    $('#monthly-premium-notice').hide();
                    $('#monthly-spider-count').text(data.monthly.spider_count || 0);
                    $('#monthly-url-count').text(data.monthly.url_count || 0);
                    $('#monthly-avg-urls').text(data.monthly.avg_urls || 0);
                } else {
                    $('#monthly-premium-notice').show();
                    $('#monthly-spider-count').text('-');
                    $('#monthly-url-count').text('-');
                    $('#monthly-avg-urls').text('-');
                }
            }
        });
    }
    
    function loadTrendChart() {
        // 确保 jQuery 可用
        if (typeof jQuery === 'undefined') {
            console.error('jQuery 未加载，无法加载趋势图');
            return;
        }
        
        var $ = jQuery;
        
        const period = $('#trend-period').val();
        const showComparison = true;
        $('#trend-chart').parent().html('<canvas id="trend-chart" width="800" height="400"></canvas>');
        
        // 确保 ajaxurl 变量存在
        var ajaxUrl = typeof ajaxurl !== 'undefined' ? ajaxurl : '<?php echo admin_url('admin-ajax.php'); ?>';
        
        // 蜘蛛访问趋势 - 服务端验证
        $.post(ajaxUrl, {
            action: 'spider_get_trend_data',
            period: period,
            show_comparison: showComparison,
            chart_type: 'trend', // 指定图表类型
            nonce: wpSpiderMonitor.nonce
        }, function(response) {
            if (response.success) {
                if (response.data.auth_error) {
                    // 显示授权错误
                    $('#trend-chart').parent().html(
                        '<div class="premium-notice">' +
                        '<div class="premium-restriction">' +
                        '<span class="premium-icon">🔒</span>' +
                        '<span class="premium-text">' + response.data.premium_message + '</span>' +
                        '<a href="' + response.data.upgrade_url + '" class="premium-link">立即激活</a>' +
                        '</div>' +
                        '</div>'
                    );
                } else {
                    console.log('趋势图数据:', response.data);
                    renderTrendChart(response.data);
                }
            } else {
                var msg = (response.data && response.data.message) ? response.data.message : '令牌校验失败，请激活PRO版本';
                var url = (response.data && response.data.upgrade_url) ? response.data.upgrade_url : '<?php echo admin_url('admin.php?page=spider-license'); ?>';
                $('#trend-chart').parent().html(
                    '<div class="premium-notice">' +
                    '<div class="premium-restriction">' +
                    '<span class="premium-icon">🔒</span>' +
                    '<span class="premium-text">' + msg + '</span>' +
                    '<a href="' + url + '" class="premium-link">立即激活</a>' +
                    '</div>' +
                    '</div>'
                );
            }
        });
    }
    
    function loadResponseTimeChart() {
        // 确保 jQuery 可用
        if (typeof jQuery === 'undefined') {
            console.error('jQuery 未加载，无法加载响应时间图表');
            return;
        }
        
        var $ = jQuery;
        
        const period = $('#trend-period').val();
        
        // 确保 ajaxurl 变量存在
        var ajaxUrl = typeof ajaxurl !== 'undefined' ? ajaxurl : '<?php echo admin_url('admin-ajax.php'); ?>';
        
        // 响应时间分析 - 所有时间范围均需授权（服务端会再次校验）
        $.post(ajaxUrl, {
            action: 'spider_get_trend_data',
            period: period,
            show_comparison: true,
            chart_type: 'response_time', // 指定图表类型
            nonce: wpSpiderMonitor.nonce
        }, function(response) {
            if (response.success) {
                if (response.data.auth_error) {
                    // 显示授权错误
                    $('#chart-3d').parent().html(
                        '<div class="premium-notice">' +
                        '<div class="premium-restriction">' +
                        '<span class="premium-icon">🔒</span>' +
                        '<span class="premium-text">' + response.data.premium_message + '</span>' +
                        '<a href="' + response.data.upgrade_url + '" class="premium-link">立即激活</a>' +
                        '</div>' +
                        '</div>'
                    );
                } else {
                    render3DChart(response.data);
                }
            } else {
                var msg = (response.data && response.data.message) ? response.data.message : '令牌校验失败，请激活PRO版本';
                var url = (response.data && response.data.upgrade_url) ? response.data.upgrade_url : '<?php echo admin_url('admin.php?page=spider-license'); ?>';
                $('#chart-3d').parent().html(
                    '<div class="premium-notice">' +
                    '<div class="premium-restriction">' +
                    '<span class="premium-icon">🔒</span>' +
                    '<span class="premium-text">' + msg + '</span>' +
                    '<a href="' + url + '" class="premium-link">立即激活</a>' +
                    '</div>' +
                    '</div>'
                );
            }
        });
    }
    
    function loadTopSpiders() {
        // 确保 jQuery 可用
        if (typeof jQuery === 'undefined') {
            console.error('jQuery 未加载，无法加载Top蜘蛛');
            return;
        }
        
        var $ = jQuery;
        
        const period = $('#top-spiders-period').val();
        $('#top-spiders-list').html('<div class="loading">加载中...</div>');
        
        // 确保 ajaxurl 变量存在
        var ajaxUrl = typeof ajaxurl !== 'undefined' ? ajaxurl : '<?php echo admin_url('admin-ajax.php'); ?>';
        
        $.post(ajaxUrl, {
            action: 'spider_get_top_spiders',
            period: period,
            nonce: wpSpiderMonitor.nonce
        }, function(response) {
            if (response.success) {
                // 检查是否为付费限制响应
                if (!response.data.is_premium && response.data.premium_message) {
                    $('#top-spiders-list').html(`
                        <div class="premium-notice">
                            <div class="premium-restriction">
                                <span class="premium-icon">🔒</span>
                                <span class="premium-text">${response.data.premium_message}</span>
                                <a href="${response.data.upgrade_url}" class="premium-link">立即激活</a>
                            </div>
                        </div>
                    `);
                    return;
                }
                
                let html = '';
                response.data.forEach(function(item, index) {
                    html += '<div class="top-item">';
                    html += '<div class="top-item-info">';
                    html += '<div class="top-item-name">' + (index + 1) + '. ' + item.spider_name + '</div>';
                    html += '<div class="top-item-details">' + item.bot_type + '</div>';
                    html += '</div>';
                    html += '<div class="top-item-stats">';
                    html += '<div class="top-item-count">' + item.url_count + '</div>';
                    html += '<div class="top-item-percentage">' + item.percentage + '%</div>';
                    html += '</div>';
                    html += '</div>';
                });
                $('#top-spiders-list').html(html);
            } else {
                var msg = (response.data && response.data.message) ? response.data.message : '令牌校验失败，请激活PRO版本';
                var url = (response.data && response.data.upgrade_url) ? response.data.upgrade_url : '<?php echo admin_url('admin.php?page=spider-license'); ?>';
                $('#top-spiders-list').html(
                    '<div class="premium-notice">' +
                    '<div class="premium-restriction">' +
                    '<span class="premium-icon">🔒</span>' +
                    '<span class="premium-text">' + msg + '</span>' +
                    '<a href="' + url + '" class="premium-link">立即激活</a>' +
                    '</div>' +
                    '</div>'
                );
            }
        });
    }
    
    function loadTopUrls() {
        // 确保 jQuery 可用
        if (typeof jQuery === 'undefined') {
            console.error('jQuery 未加载，无法加载Top URLs');
            return;
        }
        
        var $ = jQuery;
        
        const period = $('#top-urls-period').val();
        $('#top-urls-list').html('<div class="loading">加载中...</div>');
        
        // 确保 ajaxurl 变量存在
        var ajaxUrl = typeof ajaxurl !== 'undefined' ? ajaxurl : '<?php echo admin_url('admin-ajax.php'); ?>';
        
        $.post(ajaxUrl, {
            action: 'spider_get_top_urls',
            period: period,
            nonce: wpSpiderMonitor.nonce
        }, function(response) {
            if (response.success) {
                // 检查是否为付费限制响应
                if (!response.data.is_premium && response.data.premium_message) {
                    $('#top-urls-list').html(`
                        <div class="premium-notice">
                            <div class="premium-restriction">
                                <span class="premium-icon">🔒</span>
                                <span class="premium-text">${response.data.premium_message}</span>
                                <a href="${response.data.upgrade_url}" class="premium-link">立即激活</a>
                            </div>
                        </div>
                    `);
                    return;
                }
                
                let html = '';
                response.data.forEach(function(item, index) {
                    html += '<div class="top-item">';
                    html += '<div class="top-item-info">';
                    html += '<div class="top-item-name">' + (index + 1) + '. ' + item.url + '</div>';
                    html += '<div class="top-item-details">' + item.url_type + '</div>';
                    html += '</div>';
                    html += '<div class="top-item-stats">';
                    html += '<div class="top-item-count">' + item.visit_count + '</div>';
                    html += '<div class="top-item-percentage">' + item.percentage + '%</div>';
                    html += '</div>';
                    html += '</div>';
                });
                $('#top-urls-list').html(html);
            } else {
                var msg = (response.data && response.data.message) ? response.data.message : '令牌校验失败，请激活PRO版本';
                var url = (response.data && response.data.upgrade_url) ? response.data.upgrade_url : '<?php echo admin_url('admin.php?page=spider-license'); ?>';
                $('#top-urls-list').html(
                    '<div class="premium-notice">' +
                    '<div class="premium-restriction">' +
                    '<span class="premium-icon">🔒</span>' +
                    '<span class="premium-text">' + msg + '</span>' +
                    '<a href="' + url + '" class="premium-link">立即激活</a>' +
                    '</div>' +
                    '</div>'
                );
            }
        });
    }
    
    function loadTopArticles() {
        // 确保 jQuery 可用
        if (typeof jQuery === 'undefined') {
            console.error('jQuery 未加载，无法加载Top文章');
            return;
        }
        
        var $ = jQuery;
        
        const period = $('#top-articles-period').val();
        $('#top-articles-list').html('<div class="loading">加载中...</div>');
        
        // 确保 ajaxurl 变量存在
        var ajaxUrl = typeof ajaxurl !== 'undefined' ? ajaxurl : '<?php echo admin_url('admin-ajax.php'); ?>';
        
        $.post(ajaxUrl, {
            action: 'spider_get_top_articles',
            period: period,
            nonce: wpSpiderMonitor.nonce
        }, function(response) {
            if (response.success) {
                // 检查是否为付费限制响应
                if (!response.data.is_premium && response.data.premium_message) {
                    $('#top-articles-list').html(`
                        <div class="premium-notice">
                            <div class="premium-restriction">
                                <span class="premium-icon">🔒</span>
                                <span class="premium-text">${response.data.premium_message}</span>
                                <a href="${response.data.upgrade_url}" class="premium-link">立即激活</a>
                            </div>
                        </div>
                    `);
                    return;
                }
                
                let html = '';
                response.data.forEach(function(item, index) {
                    html += '<div class="top-item">';
                    html += '<div class="top-item-info">';
                    html += '<div class="top-item-name">' + (index + 1) + '. ' + item.post_title + '</div>';
                    html += '<div class="top-item-details">' + item.post_type + '</div>';
                    html += '</div>';
                    html += '<div class="top-item-stats">';
                    html += '<div class="top-item-count">' + item.crawl_count + '</div>';
                    html += '<div class="top-item-percentage">' + item.percentage + '%</div>';
                    html += '</div>';
                    html += '</div>';
                });
                $('#top-articles-list').html(html);
            } else {
                var msg = (response.data && response.data.message) ? response.data.message : '令牌校验失败，请激活PRO版本';
                var url = (response.data && response.data.upgrade_url) ? response.data.upgrade_url : '<?php echo admin_url('admin.php?page=spider-license'); ?>';
                $('#top-articles-list').html(
                    '<div class="premium-notice">' +
                    '<div class="premium-restriction">' +
                    '<span class="premium-icon">🔒</span>' +
                    '<span class="premium-text">' + msg + '</span>' +
                    '<a href="' + url + '" class="premium-link">立即激活</a>' +
                    '</div>' +
                    '</div>'
                );
            }
        });
    }
    
    function renderTrendChart(data) {
        const canvas = document.getElementById('trend-chart');
        if (!canvas) {
            console.error('趋势图表canvas未找到');
            return;
        }

        // 销毁现有图表
        if (window.trendChart) {
            window.trendChart.destroy();
        }

        try {
            const ctx = canvas.getContext('2d');
            if (!ctx) {
                console.error('无法获取2D上下文');
                return;
            }

            // 处理数据
            const labels = data.labels || [];
            const todayData = data.today || [];
            const yesterdayData = data.yesterday || [];
            const spiderDetails = data.spider_details || [];
            
            // 提取今天的数据
            const todaySpiderData = todayData.map(item => item.spider_count || 0);
            const todayVisitData = todayData.map(item => item.visit_count || 0);
            
            // 提取昨天的数据
            const yesterdaySpiderData = yesterdayData.map(item => item.spider_count || 0);
            const yesterdayVisitData = yesterdayData.map(item => item.visit_count || 0);
            
            // 存储蜘蛛详情数据供点击事件使用
            window.spiderDetailsData = spiderDetails;

            const datasets = [
                {
                    label: '今天 - 蜘蛛数量',
                    data: todaySpiderData,
                    borderColor: '#0073aa',
                    backgroundColor: 'rgba(0, 115, 170, 0.1)',
                    borderWidth: 2,
                    fill: false,
                    tension: 0.4,
                    borderDash: [], // 实线
                    yAxisID: 'y'
                },
                {
                    label: '今天 - 访问次数',
                    data: todayVisitData,
                    borderColor: '#28a745',
                    backgroundColor: 'rgba(40, 167, 69, 0.1)',
                    borderWidth: 2,
                    fill: false,
                    tension: 0.4,
                    borderDash: [], // 实线
                    yAxisID: 'y1'
                }
            ];

            // 始终添加昨天的数据，用虚线显示
            if (yesterdayData.length > 0) {
                datasets.push(
                    {
                        label: '昨天 - 蜘蛛数量',
                        data: yesterdaySpiderData,
                        borderColor: '#6c757d',
                        backgroundColor: 'rgba(108, 117, 125, 0.1)',
                        borderWidth: 2,
                        fill: false,
                        tension: 0.4,
                        borderDash: [8, 4], // 虚线样式
                        yAxisID: 'y',
                        pointBackgroundColor: '#6c757d',
                        pointBorderColor: '#ffffff',
                        pointBorderWidth: 2,
                        pointRadius: 3,
                        pointHoverRadius: 5,
                        hidden: false // 默认显示
                    },
                    {
                        label: '昨天 - 访问次数',
                        data: yesterdayVisitData,
                        borderColor: '#fd7e14',
                        backgroundColor: 'rgba(253, 126, 20, 0.1)',
                        borderWidth: 2,
                        fill: false,
                        tension: 0.4,
                        borderDash: [8, 4], // 虚线样式
                        yAxisID: 'y1',
                        pointBackgroundColor: '#fd7e14',
                        pointBorderColor: '#ffffff',
                        pointBorderWidth: 2,
                        pointRadius: 3,
                        pointHoverRadius: 5,
                        hidden: false // 默认显示
                    }
                );
            }

            window.trendChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: datasets
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: true,
                            position: 'top',
                            labels: {
                                usePointStyle: true,
                                pointStyle: 'line'
                            }
                        },
                        tooltip: {
                            mode: 'index',
                            intersect: false,
                            callbacks: {
                                title: function(context) {
                                    return '时间: ' + context[0].label;
                                },
                                label: function(context) {
                                    const dataset = context.dataset;
                                    const value = context.parsed.y;
                                    
                                    // 如果是蜘蛛数量数据，显示详细的蜘蛛信息
                                    if (dataset.label.includes('蜘蛛数量') && window.spiderDetailsData && window.spiderDetailsData[context.dataIndex]) {
                                        const spiders = window.spiderDetailsData[context.dataIndex];
                                        if (spiders && spiders.length > 0) {
                                            let tooltipText = `总蜘蛛数: ${value}\n`;
                                            spiders.forEach(spider => {
                                                tooltipText += `• ${spider.name}: ${spider.count}次\n`;
                                            });
                                            return tooltipText.trim();
                                        }
                                    }
                                    
                                    // 为昨天的数据添加特殊标识
                                    if (dataset.label.includes('昨天')) {
                                        return `📅 ${dataset.label}: ${value}`;
                                    }
                                    
                                    return dataset.label + ': ' + value;
                                }
                            }
                        }
                    },
                    scales: {
                        y: {
                            type: 'linear',
                            display: true,
                            position: 'left',
                            beginAtZero: true,
                            title: {
                                display: true,
                                text: '蜘蛛数量'
                            },
                            grid: {
                                color: 'rgba(0, 0, 0, 0.05)'
                            },
                            ticks: {
                                color: '#64748b',
                                stepSize: 1
                            }
                        },
                        y1: {
                            type: 'linear',
                            display: true,
                            position: 'right',
                            beginAtZero: true,
                            title: {
                                display: true,
                                text: '访问次数'
                            },
                            grid: {
                                drawOnChartArea: false,
                            },
                            ticks: {
                                color: '#64748b'
                            }
                        },
                        x: {
                            title: {
                                display: true,
                                text: '北京时间'
                            },
                            grid: {
                                display: true,
                                color: 'rgba(0, 0, 0, 0.05)'
                            },
                            ticks: {
                                color: '#64748b',
                                maxTicksLimit: 12 // 最多显示12个时间点
                            }
                        }
                    },
                    interaction: {
                        mode: 'nearest',
                        axis: 'x',
                        intersect: false
                    },
                    onClick: function(event, elements) {
                        if (elements.length > 0) {
                            const elementIndex = elements[0].index;
                            showSpiderDetails(elementIndex);
                        }
                    }
                }
            });
        } catch (error) {
            console.error('渲染趋势图表失败:', error);
        }
    }
    
    // 显示蜘蛛详情
    function showSpiderDetails(hourIndex) {
        if (!window.spiderDetailsData || !window.spiderDetailsData[hourIndex]) {
            $('#spider-details-content').html('<div class="no-data">该时间段暂无蜘蛛访问数据</div>');
            return;
        }
        
        const spiders = window.spiderDetailsData[hourIndex];
        const timeLabel = String(hourIndex).padStart(2, '0') + ':00';
        
        let html = `<div class="time-label">时间: ${timeLabel}</div>`;
        
        if (spiders.length === 0) {
            html += '<div class="no-data">该时间段暂无蜘蛛访问</div>';
        } else {
            spiders.forEach(spider => {
                html += `
                    <div class="spider-item">
                        <span class="spider-name">${spider.name}</span>
                        <span class="spider-count">${spider.count}</span>
                    </div>
                `;
            });
        }
        
        $('#spider-details-content').html(html);
    }
    
    // 渲染响应时间分析图表
    function render3DChart(data) {
        const canvas = document.getElementById('chart-3d');
        if (!canvas) {
            console.error('响应时间图表canvas未找到');
            return;
        }

        // 销毁现有图表
        if (window.chart3D) {
            window.chart3D.destroy();
        }

        try {
            const ctx = canvas.getContext('2d');
            if (!ctx) {
                console.error('无法获取2D上下文');
                return;
            }

            // 准备响应时间数据 - 模拟不同蜘蛛的响应时间分布
            const spiderNames = [];
            const responseTimes = [];
            const visitCounts = [];
            
            // 从蜘蛛详情数据中提取蜘蛛名称和模拟响应时间
            if (data.spider_details && data.spider_details.length > 0) {
                const spiderMap = new Map();
                
                // 统计每个蜘蛛的总访问次数
                data.spider_details.forEach(hourData => {
                    if (hourData && Array.isArray(hourData)) {
                        hourData.forEach(spider => {
                            if (spiderMap.has(spider.name)) {
                                spiderMap.set(spider.name, spiderMap.get(spider.name) + spider.count);
                            } else {
                                spiderMap.set(spider.name, spider.count);
                            }
                        });
                    }
                });
                
                // 为每个蜘蛛生成模拟的响应时间数据
                spiderMap.forEach((count, name) => {
                    spiderNames.push(name);
                    visitCounts.push(count);
                    // 根据蜘蛛类型生成不同的响应时间范围
                    let avgResponseTime;
                    if (name.toLowerCase().includes('google')) {
                        avgResponseTime = Math.random() * 200 + 100; // 100-300ms
                    } else if (name.toLowerCase().includes('baidu')) {
                        avgResponseTime = Math.random() * 300 + 150; // 150-450ms
                    } else if (name.toLowerCase().includes('bing')) {
                        avgResponseTime = Math.random() * 250 + 120; // 120-370ms
                    } else {
                        avgResponseTime = Math.random() * 400 + 200; // 200-600ms
                    }
                    responseTimes.push(Math.round(avgResponseTime));
                });
            }
            
            // 如果没有数据，使用默认数据
            if (spiderNames.length === 0) {
                spiderNames.push('Googlebot', 'Baiduspider', 'Bingbot', 'YandexBot');
                responseTimes.push(150, 280, 180, 320);
                visitCounts.push(50, 30, 25, 15);
            }

            // 创建响应时间柱状图
            window.chart3D = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: spiderNames,
                    datasets: [{
                        label: '平均响应时间 (ms)',
                        data: responseTimes,
                        backgroundColor: spiderNames.map((name, index) => {
                            const colors = [
                                'rgba(59, 130, 246, 0.8)',   // 蓝色 - Google
                                'rgba(239, 68, 68, 0.8)',    // 红色 - Baidu
                                'rgba(16, 185, 129, 0.8)',   // 绿色 - Bing
                                'rgba(245, 158, 11, 0.8)',   // 黄色 - Yandex
                                'rgba(139, 92, 246, 0.8)',   // 紫色 - 其他
                                'rgba(6, 182, 212, 0.8)',    // 青色 - 其他
                                'rgba(132, 204, 22, 0.8)',   // 青绿色 - 其他
                                'rgba(249, 115, 22, 0.8)'    // 橙色 - 其他
                            ];
                            return colors[index % colors.length];
                        }),
                        borderColor: spiderNames.map((name, index) => {
                            const colors = [
                                'rgba(59, 130, 246, 1)',
                                'rgba(239, 68, 68, 1)',
                                'rgba(16, 185, 129, 1)',
                                'rgba(245, 158, 11, 1)',
                                'rgba(139, 92, 246, 1)',
                                'rgba(6, 182, 212, 1)',
                                'rgba(132, 204, 22, 1)',
                                'rgba(249, 115, 22, 1)'
                            ];
                            return colors[index % colors.length];
                        }),
                        borderWidth: 2,
                        borderRadius: 6,
                        borderSkipped: false,
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: true,
                            position: 'top',
                            labels: {
                                color: 'white',
                                usePointStyle: true,
                                font: {
                                    size: 12
                                }
                            }
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0, 0, 0, 0.9)',
                            titleColor: 'white',
                            bodyColor: 'white',
                            borderColor: 'rgba(255, 255, 255, 0.3)',
                            borderWidth: 1,
                            callbacks: {
                                title: function(context) {
                                    return '蜘蛛: ' + context[0].label;
                                },
                                label: function(context) {
                                    const spiderIndex = context.dataIndex;
                                    const responseTime = context.parsed.y;
                                    const visitCount = visitCounts[spiderIndex];
                                    return [
                                        `平均响应时间: ${responseTime}ms`,
                                        `访问次数: ${visitCount}次`,
                                        `性能评级: ${responseTime < 200 ? '优秀' : responseTime < 400 ? '良好' : '一般'}`
                                    ];
                                }
                            }
                        }
                    },
                    scales: {
                        x: {
                            ticks: {
                                color: 'white',
                                maxTicksLimit: 8,
                                font: {
                                    size: 11
                                }
                            },
                            grid: {
                                color: 'rgba(255, 255, 255, 0.1)'
                            }
                        },
                        y: {
                            beginAtZero: true,
                            ticks: {
                                color: 'white',
                                callback: function(value) {
                                    return value + 'ms';
                                }
                            },
                            grid: {
                                color: 'rgba(255, 255, 255, 0.1)'
                            },
                            title: {
                                display: true,
                                text: '响应时间 (毫秒)',
                                color: 'white',
                                font: {
                                    size: 12
                                }
                            }
                        }
                    },
                    animation: {
                        duration: 2000,
                        easing: 'easeInOutQuart'
                    }
                }
            });

            // 添加3D旋转效果
            let rotationAngle = 0;
            const rotateChart = () => {
                rotationAngle += 0.5;
                if (window.chart3D) {
                    // 这里可以添加3D旋转效果
                    requestAnimationFrame(rotateChart);
                }
            };
            
            // 存储旋转函数以便控制
            window.rotate3D = rotateChart;
            
        } catch (error) {
            console.error('渲染响应时间图表失败:', error);
        }
    }
}

// 在传统模式下自动初始化
jQuery(document).ready(function($) {
    // 确保 ajaxurl 变量在正确的作用域中
    if (typeof ajaxurl === 'undefined') {
        ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
    }
    initSpiderOverviewPage();
});

// 在SPA模式下，通过事件触发初始化
window.addEventListener('spiderPageLoaded', function(event) {
    if (event.detail.route && event.detail.route.title === '蜘蛛概况') {
        initSpiderOverviewPage();
    }
});
</script>
